from tortoise import Model, fields


class UserInDB(Model):
    id = fields.IntField(pk=True, description="用户id")
    username = fields.CharField(max_length=20, unique=True, db_index=True, null=False, description="用户名")
    password = fields.CharField(max_length=255, min_length=8, null=False, description="密码")
    is_frozen = fields.BooleanField(default=False, description="是否被冻结")
    is_admin = fields.BooleanField(default=False, description="是否为管理员")
    avatar = fields.CharField(null=True, max_length=255, description="头像")
    update_at = fields.DatetimeField(auto_now=True, description="更新时间")
    create_at = fields.DatetimeField(auto_now_add=True, description="创建时间")

    roles = fields.ManyToManyField("models.RoleInDB", db_constraint=False, related_name="users")

    class Meta:
        ordering = ["-create_at"]

    class PydanticMeta:
        exclude = ["password"]  # 指定序列化时需要忽略的属性


class RoleInDB(Model):
    id = fields.IntField(pk=True, description="角色id")
    name = fields.CharField(max_length=50, unique=True, db_index=True, null=False, description="角色名")
    update_at = fields.DatetimeField(auto_now=True, description="更新时间")
    create_at = fields.DatetimeField(auto_now_add=True, description="创建时间")

    permissions = fields.ManyToManyField("models.PermissionInDB", db_constraint=False, related_name="roles")

    class Meta:
        ordering = ["-create_at"]


class PermissionInDB(Model):
    id = fields.IntField(pk=True, description="权限id")
    code = fields.IntField(unique=True, db_index=True, null=False, description="权限代码")
    description = fields.CharField(max_length=255, description="权限描述")
